/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "http_request.h"
#include <event2/keyvalq_struct.h>
#include <event2/buffer.h>

namespace node {
    namespace http {

        HttpRequest::HttpRequest(struct evhttp_request * request)
            : request_(request)
            , method_(0)
            , headers_()
            , input_(NULL)
            , decoded_(NULL)
            , parse_ok_(true)
        {
            Initialize();
        }

        HttpRequest::~HttpRequest(void)
        {
            if (decoded_ != NULL) {
                evhttp_uri_free(decoded_);
            }
        }

        void HttpRequest::Initialize(void)
        {
            assert(request_ != NULL);

            // parse method
            method_ = evhttp_request_get_command(request_);
            // parse header
            struct evkeyvalq * headers = evhttp_request_get_input_headers(request_);
            for (struct evkeyval *header = headers->tqh_first; header;
                header = header->next.tqe_next) {
                headers_[header->key] = header->value;
            }
            // uri
            decoded_ = evhttp_uri_parse(evhttp_request_get_uri(request_));
            if (!decoded_) {
                evhttp_send_error(request_, HTTP_BADREQUEST, 0);
                parse_ok_ = false;
            }
            // input data
            input_ = evhttp_request_get_input_buffer(request_);
        }

        ::std::size_t HttpRequest::get_input_size(void) const {
            assert(input_ != NULL);
            return evbuffer_get_length(input_);
        }

        int HttpRequest::Read(char *buffer, int size)
        {
            assert(input_ != NULL);
            return evbuffer_remove(input_, buffer, size);
        }
    }
}